<template>
  <div class="public-role-details-page">
    <div class="container">
      <div v-if="loading" class="loading-container">
        <div class="loading-spinner"></div>
        <p>加载中...</p>
      </div>
      
      <div v-else-if="!role" class="error-state">
        <div class="error-icon">❌</div>
        <h3>角色不存在</h3>
        <p>该角色可能已被删除或不存在</p>
        <button class="back-btn" @click="$router.back()">返回</button>
      </div>
      
      <div v-else class="role-details">
        <!-- 角色头部信息 -->
        <div class="role-header">
          <div class="role-avatar">
            <img v-if="role.avatarUrl" :src="role.avatarUrl" :alt="role.name" />
            <div v-else class="avatar-placeholder">{{ role.name.charAt(0) }}</div>
          </div>
          
          <div class="role-info">
            <h1 class="role-name">{{ role.name }}</h1>
            <p class="role-desc">{{ role.description || '暂无描述' }}</p>
            
            <div class="role-stats">
              <div class="stat">
                <span class="stat-icon">💬</span>
                <span class="stat-value">{{ role.usageCount || 0 }}</span>
                <span class="stat-label">使用次数</span>
              </div>
              <div class="stat">
                <span class="stat-icon">⭐</span>
                <span class="stat-value">{{ role.averageRating || 0 }}</span>
                <span class="stat-label">平均评分</span>
              </div>
              <div class="stat">
                <span class="stat-icon">❤️</span>
                <span class="stat-value">{{ role.favoriteCount || 0 }}</span>
                <span class="stat-label">收藏数</span>
              </div>
              <div class="stat">
                <span class="stat-icon">📅</span>
                <span class="stat-value">{{ formatDate(role.createdAt) }}</span>
                <span class="stat-label">创建时间</span>
              </div>
            </div>
            
            <div v-if="role.tags" class="role-tags">
              <span v-for="tag in role.tags.split(',')" :key="tag" class="tag">
                {{ tag.trim() }}
              </span>
            </div>
          </div>
          
          <div class="role-actions">
            <button class="action-btn primary" @click="startChat">
              <span class="btn-icon">💬</span>
              开始对话
            </button>
            <button class="action-btn" @click="toggleFavorite">
              <span class="btn-icon">{{ role.isFavorited ? '❤️' : '🤍' }}</span>
              {{ role.isFavorited ? '已收藏' : '收藏' }}
            </button>
            <button class="action-btn" @click="shareRole">
              <span class="btn-icon">📤</span>
              分享
            </button>
          </div>
        </div>
        
        <!-- 角色详细信息 -->
        <div class="role-content">
          <div class="content-section">
            <h3 class="section-title">角色设定</h3>
            <div class="section-content">
              <div v-if="role.personality" class="info-item">
                <label>性格特点</label>
                <p>{{ role.personality }}</p>
              </div>
              <div v-if="role.background" class="info-item">
                <label>背景故事</label>
                <p>{{ role.background }}</p>
              </div>
              <div v-if="role.speakingStyle" class="info-item">
                <label>说话风格</label>
                <p>{{ role.speakingStyle }}</p>
              </div>
            </div>
          </div>
          
          <div class="content-section">
            <h3 class="section-title">开场白</h3>
            <div class="section-content">
              <div class="opening-line">
                <p>{{ role.openingLine || '暂无开场白' }}</p>
              </div>
            </div>
          </div>
          
          <div class="content-section">
            <h3 class="section-title">用户评价</h3>
            <div class="section-content">
              <div v-if="reviews.length === 0" class="no-reviews">
                <p>暂无用户评价</p>
              </div>
              <div v-else class="reviews-list">
                <div v-for="review in reviews" :key="review.id" class="review-item">
                  <div class="review-header">
                    <div class="reviewer-info">
                      <div class="reviewer-avatar">{{ review.userName.charAt(0) }}</div>
                      <div class="reviewer-details">
                        <span class="reviewer-name">{{ review.userName }}</span>
                        <div class="review-rating">
                          <span v-for="i in 5" :key="i" class="star" :class="{ filled: i <= review.rating }">⭐</span>
                        </div>
                      </div>
                    </div>
                    <span class="review-date">{{ formatDate(review.createdAt) }}</span>
                  </div>
                  <p class="review-content">{{ review.comment }}</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()
const loading = ref(true)
const role = ref(null)
const reviews = ref([])

const loadRoleDetails = async () => {
  try {
    const res = await fetch(`/api/roles/public/${route.params.id}`)
    const data = await res.json()
    
    if (data.code === 0) {
      role.value = data.data
      await loadReviews()
    } else {
      console.error('获取角色详情失败:', data.message)
    }
  } catch (e) {
    console.error('获取角色详情失败', e)
  } finally {
    loading.value = false
  }
}

const loadReviews = async () => {
  try {
    const res = await fetch(`/api/roles/${route.params.id}/reviews`)
    const data = await res.json()
    
    if (data.code === 0) {
      reviews.value = data.data || []
    }
  } catch (e) {
    console.error('获取评价失败', e)
  }
}

const startChat = () => {
  router.push(`/chat/${role.value.id}`)
}

const toggleFavorite = async () => {
  try {
    const token = localStorage.getItem('auth_token')
    if (!token) {
      router.push('/login')
      return
    }
    
    const res = await fetch(`/api/roles/${role.value.id}/favorite`, {
      method: 'POST',
      headers: { 'Authorization': `Bearer ${token}` }
    })
    
    const data = await res.json()
    if (data.code === 0) {
      role.value.isFavorited = !role.value.isFavorited
      role.value.favoriteCount = (role.value.favoriteCount || 0) + (role.value.isFavorited ? 1 : -1)
    } else {
      console.error('收藏操作失败:', data.message)
    }
  } catch (e) {
    console.error('收藏操作失败', e)
  }
}

const shareRole = () => {
  const url = window.location.href
  if (navigator.share) {
    navigator.share({
      title: role.value.name,
      text: role.value.description,
      url: url
    })
  } else {
    navigator.clipboard.writeText(url).then(() => {
      alert('链接已复制到剪贴板')
    })
  }
}

const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

onMounted(() => {
  loadRoleDetails()
})
</script>

<style scoped>
.public-role-details-page {
  min-height: 100vh;
  background: #f8fafc;
  padding: 20px 0;
}

.container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 0 20px;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 400px;
  color: #6b7280;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #e5e7eb;
  border-top: 4px solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-state {
  text-align: center;
  padding: 80px 20px;
  color: #6b7280;
}

.error-icon {
  font-size: 4rem;
  margin-bottom: 16px;
}

.error-state h3 {
  font-size: 1.5rem;
  font-weight: 600;
  color: #374151;
  margin-bottom: 8px;
}

.back-btn {
  padding: 12px 24px;
  background: #667eea;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 500;
  margin-top: 16px;
}

.role-details {
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 6px rgba(0,0,0,0.05);
  overflow: hidden;
}

.role-header {
  padding: 40px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  display: flex;
  gap: 24px;
  align-items: flex-start;
}

.role-avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  overflow: hidden;
  background: rgba(255,255,255,0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.role-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  color: white;
  font-size: 48px;
  font-weight: 600;
}

.role-info {
  flex: 1;
}

.role-name {
  font-size: 2rem;
  font-weight: 700;
  margin-bottom: 8px;
}

.role-desc {
  font-size: 1.125rem;
  opacity: 0.9;
  margin-bottom: 24px;
  line-height: 1.5;
}

.role-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: 16px;
  margin-bottom: 16px;
}

.stat {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.stat-icon {
  font-size: 1.5rem;
  margin-bottom: 4px;
}

.stat-value {
  font-size: 1.25rem;
  font-weight: 600;
  margin-bottom: 2px;
}

.stat-label {
  font-size: 0.875rem;
  opacity: 0.8;
}

.role-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tag {
  background: rgba(255,255,255,0.2);
  color: white;
  padding: 6px 12px;
  border-radius: 16px;
  font-size: 0.875rem;
  font-weight: 500;
}

.role-actions {
  display: flex;
  flex-direction: column;
  gap: 12px;
  flex-shrink: 0;
}

.action-btn {
  padding: 12px 20px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  gap: 8px;
  min-width: 140px;
  justify-content: center;
}

.action-btn.primary {
  background: white;
  color: #667eea;
}

.action-btn.primary:hover {
  background: #f8fafc;
  transform: translateY(-1px);
}

.action-btn:not(.primary) {
  background: rgba(255,255,255,0.2);
  color: white;
  border: 1px solid rgba(255,255,255,0.3);
}

.action-btn:not(.primary):hover {
  background: rgba(255,255,255,0.3);
}

.btn-icon {
  font-size: 16px;
}

.role-content {
  padding: 40px;
}

.content-section {
  margin-bottom: 32px;
}

.section-title {
  font-size: 1.25rem;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 2px solid #e5e7eb;
}

.section-content {
  color: #374151;
  line-height: 1.6;
}

.info-item {
  margin-bottom: 16px;
}

.info-item label {
  display: block;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 4px;
}

.opening-line {
  background: #f8fafc;
  padding: 16px;
  border-radius: 8px;
  border-left: 4px solid #667eea;
  font-style: italic;
}

.no-reviews {
  text-align: center;
  color: #6b7280;
  padding: 40px;
}

.reviews-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.review-item {
  background: #f8fafc;
  padding: 16px;
  border-radius: 8px;
  border: 1px solid #e5e7eb;
}

.review-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.reviewer-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.reviewer-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: #667eea;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  font-size: 14px;
}

.reviewer-name {
  font-weight: 600;
  color: #1f2937;
}

.review-rating {
  display: flex;
  gap: 2px;
}

.star {
  font-size: 14px;
  opacity: 0.3;
}

.star.filled {
  opacity: 1;
}

.review-date {
  font-size: 0.875rem;
  color: #6b7280;
}

.review-content {
  color: #374151;
  line-height: 1.5;
}

@media (max-width: 768px) {
  .role-header {
    flex-direction: column;
    text-align: center;
  }
  
  .role-actions {
    flex-direction: row;
    justify-content: center;
  }
  
  .role-stats {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .role-content {
    padding: 20px;
  }
}
</style>

